#include <REGX52.H>
#include"LCD1602.h"
/*
//using key

//detect
char key_detect()
{
	unsigned char a = 0;
	P1 = 0xFF;
	//change column
	P1_0 = 0;
	if(P1_4 == 0)
	{
		while(P1_4 == 0)
			;
		a = 1;
	}
	if(P1_5 == 0)
	{
		while(P1_5 == 0)
			;
		a = 2;
	}
	return a;
}

int main()
{
	LCD_Init();
	//char a = 0;
	//char e = 0;
	//char b = 0;
	//char c = 0;
	//while(!b)
	//	b = key_detect();
	LCD_ShowNum(1,1,23,4);
	while(2)
	{
		;
	}
	
	return 0;
}
*/

/*
int main()
{
	LCD_Init();
	LCD_ShowNum(1,1,1,4);
	while(1)
		;
	return 0;
}*/

/*
int key(char b)
{
	char a = b;
	//all change one
	P1 = 0xFF;
	P1_7 = 0;
	if(P1_3 == 0)
		return 0;
	if(P1_2 == 0)
		return 1;
	if(P1_1 == 0)
		return 2;
	if(P1_0 == 0)
		return 3;
	P1_6 = 0;
	if(P1_3 == 0)
		return 4;
	if(P1_2 == 0)
		return 5;
	if(P1_1 == 0)
		return 6;
	if(P1_0 == 0)
		return 7;
	P1_5 = 0;
	if(P1_3 == 0)
		return 8;
	if(P1_2 == 0)
		return 9;
	if(P1_1 == 0)
		return 10;
	if(P1_0 == 0)
		return 11;
	P1_4 = 0;
	if(P1_3 == 0)
		return 12;
	if(P1_2 == 0)
		return 13;
	if(P1_1 == 0)
		return 14;
	if(P1_0 == 0)
		return 15;
	return a;

}*/
#include<intrins.h>

void time(char a)
{
	while(a--)
	{
	_nop_();
	_nop_();
	_nop_();
	}
}

char key()
{
	char b = 0;
	char a = 0;
	P1 = 0x0f;
	if(P1_0 == 0)
		a = 4;
	else if(P1_1 == 0)
		a = 3;
	else if(P1_2 == 0)
		a = 2;
	else if(P1_3 == 0)
		a = 1;
	else 
		return 0;
	time(1);
	P1 = 0xf0;
	if(P1_4 == 0)
		a += 12;
	else if(P1_5 == 0)
		a += 8;
	else if(P1_6 == 0)
		a += 4;
	
	while(b < 50 && P1 != 0xf0)
	{
		time(100000);
		b++;
	}
	
	if(b >= 50)
		return 0;
	return a;
}        


int main()
{
	char i = 0;
	char z = 4;
	char a[5] = "0000";
	char t = 0;
	begin:

	while(1)
	{
				for(i = 0; i < 5; i++)
		{
			a[i] = '0';
		}
		
		LCD_Init();
		z = 5;
		while(z > 0)
		{
			char b = key();
		if(b != 0)
		{
					switch(b)
				{
					case 1:b = 0;break;
					case 2: b = 1;break;
					case 3 : b = 2;break;
					case 4:z = 0;break;
					case 5:b = 3;break;
					case 6:b = 4;break;
					case 7:b = 5;break;
					case 8:if(z < 5)a[z] = 0;z++;break;
					case 9:b = 6;break;
					case 10:b = 7;break;
					case 11:b = 8;break;
					case 12 : goto begin;
					case 13:b = 20;
					case 14:b = 9; break;
					case 15:b = 20;break;
				}
				
				if(z > 0&& b != 20)
				{
					for(i = 0;i < 3; i++)
						a[i] = a[i + 1];
					
					a[3] = b + '0';
					z--;
				}
			
			}
			
			
			for(i = 0; i < 4; i++)
			{
				LCD_ShowChar(2,i + 1,a[i]);
			}
			//LCD_ShowNum(2,1,a,4);
		}
		
		z = 0;
		for(i = 0; i < 4; i++)
		{
			if(a[i] != i + '0')
			{
				z = 1;
				break;
			}
		}
		if(z)
		{
			z = 5;
			while(z--)
			{
				LCD_ShowString(1,1,"err");
				t = 1000;
				while(t--)
					time(1000);
			}
		}
		else
		{
				while(1)
			{
				LCD_ShowString(1,1,"happy");
			}
		}
	}
}
/*
int main()
{

	char b = 0;
	char a = 0;
	LCD_Init();
	while(1)
	{
		b = key();
		if(b != 0)
			a = b - 1;
		LCD_ShowNum(1,1,a,2);
	}

}
*/

/*
int main()
{
	LCD_Init();
	LCD_ShowNum(1,1,1,1);
	while(1)
	{;}
}*/